package com.zheng.oss.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.zheng.oss.common.constant.OssResult;
import com.zheng.oss.common.constant.OssResultConstant;
import com.zheng.oss.dto.FileInfo;
import com.zheng.oss.web.service.LocalUploadService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * Created by likun on 2018/4/19.
 */
@Controller
@RequestMapping("/local")
public class LocalUploadController {

    private static Logger _log = LoggerFactory.getLogger(LocalUploadController.class);

    @Value("${local.upload.dir}")
    private String uploadFolder;

    @Autowired
    private LocalUploadService localUploadService;


    //大文件上传
    @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
    @ResponseBody
    public Object fileUpload(String status, FileInfo info, @RequestParam(value = "file", required = false) MultipartFile file){
        JSONObject data = new JSONObject();
        if(status == null){	//文件上传
            if(file != null && !file.isEmpty()){	//验证请求不会包含数据上传，所以避免NullPoint这里要检查一下file变量是否为null
                try {
                    File target = localUploadService.getReadySpace(info, this.uploadFolder );	//为上传的文件准备好对应的位置
                    if(target == null){
                        data.put("status", 0);
                        data.put("message", localUploadService.getErrorMsg());
                        return new OssResult(OssResultConstant.FAILED, data);
                    }
                    file.transferTo(target);	//保存上传文件

                    //将MD5签名和合并后的文件path存入持久层，注意这里这个需求导致需要修改webuploader.js源码3170行
                    //因为原始webuploader.js不支持为formData设置函数类型参数，这将导致不能在控件初始化后修改该参数
                    if(info.getChunks() <= 0){
                        if(!localUploadService.saveMd52FileMap(info.getMd5(), target.getName())){
                            _log.error("文件[" + info.getMd5() + "=>" + target.getName() + "]保存关系到持久成失败，但并不影响文件上传，只会导致日后该文件可能被重复上传而已");
                        }
                    }

                    data.put("status", 1);
                    data.put("path", target.getName());
                    return new OssResult(OssResultConstant.SUCCESS, data);

                }catch(IOException ex){
                    _log.error("数据上传失败", ex);
                    data.put("status", 0);
                    data.put("message", "数据上传失败");
                    return new OssResult(OssResultConstant.FAILED, data);
                }
            }
        }else{
            if(status.equals("md5Check")){	//秒传验证
                String path = localUploadService.md5Check(info.getMd5());
                if(path == null){
                    data.put("ifExist", 0);
                    return new OssResult(OssResultConstant.SUCCESS, data);
                }else{
                    data.put("ifExist", 1);
                    data.put("path", path);
                    return new OssResult(OssResultConstant.SUCCESS, data);
                }

            }else if(status.equals("chunkCheck")){	//分块验证
                //检查目标分片是否存在且完整
                if(localUploadService.chunkCheck(this.uploadFolder + "/" + info.getName() + "/" + info.getChunkIndex(), Long.valueOf(info.getSize()))){
                    data.put("ifExist", 1);
                    return new OssResult(OssResultConstant.SUCCESS, data);
                }else{
                    data.put("ifExist", 0);
                    return new OssResult(OssResultConstant.SUCCESS, data);
                }

            }else if(status.equals("chunksMerge")){	//分块合并

                String path = localUploadService.chunksMerge(info.getName(), info.getExt(), info.getChunks(), info.getMd5(), this.uploadFolder);
                if(path == null){
                    data.put("status", 0);
                    data.put("message", localUploadService.getErrorMsg());
                    return new OssResult(OssResultConstant.FAILED, data);
                }

                data.put("status", 1);
                data.put("path", path);
                data.put("message", "中文测试");
                return new OssResult(OssResultConstant.SUCCESS, data);
            }
        }
        _log.error("请求参数不完整");
        data.put("status", 0);
        data.put("message", "请求参数不完整");
        return new OssResult(OssResultConstant.FAILED, data);
    }

}
